package com.have.blog.web.config;

import com.have.blog.model.models.User;
import com.have.blog.web.constant.BlogConstant;
import com.have.blog.web.redis.UserRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserRedisService userRedisService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //得到请求头信息authorization信息
        String accessToken = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(accessToken) && accessToken.startsWith("Bearer ")) {
            accessToken = accessToken.substring("Bearer ".length());
            User user = userRedisService.getUserByToken(accessToken);
            if (user != null) {
                //把userUid存储到 request中
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new User(), null, null));
                request.setAttribute(BlogConstant.TOKEN, accessToken);
                request.setAttribute(BlogConstant.USER_UID, user.getUid());
                request.setAttribute(BlogConstant.USER_NAME, user.getUsername());
                userRedisService.addUserByToken(accessToken, user);
                log.info("解析出来的用户:{}", user.getNickname());
            }
        }
        chain.doFilter(request, response);
    }
}
